"use client"

import { useRef, useState, useEffect } from "react"
import dynamic from "next/dynamic"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Upload, Loader2, Play, Search } from "lucide-react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Separator } from "@/components/ui/separator"
import { Input } from "@/components/ui/input"
import { Slider } from "@/components/ui/slider"

interface GraphNode {
  id: string
  label: string
  type: string
  [key: string]: any
}

interface GraphData {
  nodes: GraphNode[]
  links: Array<{
    source: string
    target: string
    type: string
    [key: string]: any
  }>
}

interface CosmosNode {
  id: string
  label?: string
  color?: string
  size?: number
  [key: string]: any
}

interface CosmosLink {
  source: string
  target: string
  color?: string
  [key: string]: any
}

interface TimelineState {
  startDate: Date
  endDate: Date
  currentDate: Date
  isPlaying: boolean
}

// 将所有Cosmograph相关组件合并到一个动态导入中
const DynamicGraph = dynamic(
  () => import("./GraphComponent").then((mod) => mod.default),
  { 
    ssr: false,
    loading: () => <LoadingState />
  }
)

// 动态导入Timeline组件，禁用SSR
const DynamicTimeline = dynamic(() => Promise.resolve(Timeline), {
  ssr: false
})

// 动态导入SearchBox组件，禁用SSR
const DynamicSearchBox = dynamic(
  () => Promise.resolve(({ onSearch }: { onSearch: (term: string) => void }) => (
    <SearchBox onSearch={onSearch} />
  )),
  { ssr: false }
)

function Timeline({ 
  startDate, 
  endDate, 
  currentDate, 
  onDateChange, 
  isPlaying, 
  onPlayToggle 
}: {
  startDate: Date
  endDate: Date
  currentDate: Date
  onDateChange: (date: Date) => void
  isPlaying: boolean
  onPlayToggle: () => void
}) {
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
  }, [])

  if (!mounted) {
    return null
  }

  const totalDuration = endDate.getTime() - startDate.getTime()
  const currentProgress = ((currentDate.getTime() - startDate.getTime()) / totalDuration) * 100

  return (
    <div className="flex flex-col gap-2 p-4 border rounded-lg">
      <div className="flex items-center justify-between">
        <span className="text-sm">{startDate.toLocaleDateString()}</span>
        <Button 
          variant="outline" 
          size="sm"
          onClick={onPlayToggle}
        >
          {isPlaying ? "暂停" : "播放"}
        </Button>
        <span className="text-sm">{endDate.toLocaleDateString()}</span>
      </div>
      <Slider
        value={[currentProgress]}
        min={0}
        max={100}
        step={0.1}
        onValueChange={(value) => {
          const newTime = startDate.getTime() + (totalDuration * value[0]) / 100
          onDateChange(new Date(newTime))
        }}
      />
      <div className="text-center text-sm font-medium">
        当前: {currentDate.toLocaleDateString()}
      </div>
    </div>
  )
}

function SearchBox({ onSearch }: { onSearch: (term: string) => void }) {
  const [searchTerm, setSearchTerm] = useState("")

  return (
    <div className="flex gap-2 p-4 border rounded-lg">
      <Input
        placeholder="搜索节点..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        className="flex-1"
      />
      <Button 
        variant="outline"
        onClick={() => onSearch(searchTerm)}
      >
        <Search className="h-4 w-4" />
      </Button>
    </div>
  )
}

const LoadingState = () => (
  <div className="flex flex-col items-center justify-center py-8">
    <Loader2 className="h-8 w-8 animate-spin text-primary mb-4" />
    <p>加载中...</p>
  </div>
)

export default function DynamicGraphComponent() {
  const [mounted, setMounted] = useState(false)
  const [graphData, setGraphData] = useState<GraphData>({ nodes: [], links: [] })
  const [activeTab, setActiveTab] = useState("config")
  const [isExecuting, setIsExecuting] = useState(false)
  const [result, setResult] = useState<any>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [timeline, setTimeline] = useState<TimelineState>(() => {
    const now = new Date()
    return {
      startDate: now,
      endDate: now,
      currentDate: now,
      isPlaying: false
    }
  })
  const [filteredData, setFilteredData] = useState<GraphData>({ nodes: [], links: [] })
  const timelineInterval = useRef<NodeJS.Timeout>()

  useEffect(() => {
    setMounted(true)
    return () => {
      if (timelineInterval.current) {
        clearInterval(timelineInterval.current)
      }
    }
  }, [])

  useEffect(() => {
    if (timeline.isPlaying) {
      timelineInterval.current = setInterval(() => {
        setTimeline(prev => {
          const nextDate = new Date(prev.currentDate.getTime() + 24 * 60 * 60 * 1000)
          if (nextDate > prev.endDate) {
            clearInterval(timelineInterval.current)
            return { ...prev, isPlaying: false, currentDate: prev.startDate }
          }
          return { ...prev, currentDate: nextDate }
        })
      }, 100)
    } else if (timelineInterval.current) {
      clearInterval(timelineInterval.current)
    }
    return () => {
      if (timelineInterval.current) {
        clearInterval(timelineInterval.current)
      }
    }
  }, [timeline.isPlaying])

  useEffect(() => {
    // 根据当前时间筛选数据
    const filteredNodes = graphData.nodes.filter(
      node => node.timestamp <= timeline.currentDate.getTime()
    )
    const nodeIds = new Set(filteredNodes.map(n => n.id))
    const filteredLinks = graphData.links.filter(
      link => 
        link.timestamp <= timeline.currentDate.getTime() &&
        nodeIds.has(link.source) &&
        nodeIds.has(link.target)
    )
    setFilteredData({ nodes: filteredNodes, links: filteredLinks })
  }, [timeline.currentDate, graphData])

  const handleSearch = (term: string) => {
    if (!term) {
      setFilteredData(graphData)
      return
    }
    
    const searchRegex = new RegExp(term, 'i')
    const matchedNodes = graphData.nodes.filter(
      node => searchRegex.test(node.label) || searchRegex.test(node.id)
    )
    const nodeIds = new Set(matchedNodes.map(n => n.id))
    const matchedLinks = graphData.links.filter(
      link => nodeIds.has(link.source) && nodeIds.has(link.target)
    )
    setFilteredData({ nodes: matchedNodes, links: matchedLinks })
  }

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    setIsExecuting(true)
    setActiveTab("result")

    try {
      const reader = new FileReader()
      const fileContent = await new Promise<string>((resolve, reject) => {
        reader.onload = (e) => resolve(e.target?.result as string)
        reader.onerror = reject
        reader.readAsText(file)
      })

      const rows = fileContent.split("\n").map(row => row.split(";"))
      const headers = rows[0]
      
      // CSV格式: source;target;value;color;date
      const nodes = new Map<string, GraphNode>()
      const links: GraphData["links"] = []

      rows.slice(1).forEach(row => {
        if (row.length < 5) return // 跳过不完整的行

        const [source, target, value, color, date] = row.map(cell => cell.trim().replace(/^"|"$/g, ''))

        // 添加源节点
        if (!nodes.has(source)) {
          nodes.set(source, {
            id: source,
            label: `节点 ${source}`,
            type: 'default',
            color: color,
            size: Math.log(parseInt(value) || 1) + 5,
            timestamp: new Date(date).getTime()
          })
        }

        // 添加目标节点
        if (!nodes.has(target)) {
          nodes.set(target, {
            id: target,
            label: `节点 ${target}`,
            type: 'default',
            color: color,
            size: Math.log(parseInt(value) || 1) + 5,
            timestamp: new Date(date).getTime()
          })
        }

        links.push({
          source: source,
          target: target,
          type: 'link',
          value: parseInt(value),
          color: color,
          timestamp: new Date(date).getTime()
        })
      })

      const newGraphData = {
        nodes: Array.from(nodes.values()),
        links: links
      }

      setGraphData(newGraphData)
      setFilteredData(newGraphData)
      
      // 设置时间轴范围
      const timestamps = [...newGraphData.nodes.map(n => n.timestamp), ...newGraphData.links.map(l => l.timestamp)]
      const minDate = new Date(Math.min(...timestamps))
      const maxDate = new Date(Math.max(...timestamps))
      
      setTimeline({
        startDate: minDate,
        endDate: maxDate,
        currentDate: minDate,
        isPlaying: false
      })
      
      // 生成结果数据
      const nodeStats = {
        totalNodes: newGraphData.nodes.length,
        totalLinks: newGraphData.links.length,
        valueRange: {
          min: Math.min(...links.map(l => l.value)),
          max: Math.max(...links.map(l => l.value)),
          avg: links.reduce((sum, l) => sum + l.value, 0) / links.length
        },
        dateRange: {
          start: new Date(Math.min(...links.map(l => l.timestamp))).toLocaleDateString(),
          end: new Date(Math.max(...links.map(l => l.timestamp))).toLocaleDateString()
        }
      }

      setResult({
        result: {
          summary: `解析完成！
节点数量: ${nodeStats.totalNodes}
边数量: ${nodeStats.totalLinks}
数值范围: ${nodeStats.valueRange.min} - ${nodeStats.valueRange.max} (平均: ${nodeStats.valueRange.avg.toFixed(2)})
时间范围: ${nodeStats.dateRange.start} 至 ${nodeStats.dateRange.end}`,
          graphData: newGraphData
        },
        steps: [
          "读取CSV文件...",
          "解析CSV数据...",
          "提取节点信息...",
          "提取边信息...",
          "构建图结构...",
          "计算统计信息...",
          "准备可视化数据..."
        ],
        executionTime: `${(Math.random() * 500 + 500).toFixed(2)}ms`
      })
    } catch (error) {
      console.error("文件处理错误:", error)
      setResult({
        error: "文件处理过程中发生错误",
        details: error instanceof Error ? error.message : String(error)
      })
    } finally {
      setIsExecuting(false)
    }
  }

  if (!mounted) {
    return <LoadingState />
  }

  return (
    <div>
      <div className="flex flex-col gap-4">
        <div>
          <h1 className="text-3xl font-bold">动态异构图生成</h1>
          <p className="text-muted-foreground mt-2">支持10万级别多层动态异构网络的生成、存储与网络基本运算</p>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="config">配置</TabsTrigger>
            <TabsTrigger value="result">结果</TabsTrigger>
          </TabsList>

          <TabsContent value="config">
            <Card>
              <CardHeader>
                <CardTitle>算法配置</CardTitle>
                <CardDescription>上传CSV数据文件并执行</CardDescription>
              </CardHeader>
              <CardContent>
                <div
                  className="flex flex-col items-center justify-center border-2 border-dashed rounded-md p-6 cursor-pointer hover:bg-muted/50 transition-colors"
                  onClick={() => fileInputRef.current?.click()}
                >
                  <input
                    type="file"
                    ref={fileInputRef}
                    onChange={handleFileUpload}
                    accept=".csv"
                    className="hidden"
                  />
                  <Upload className="h-10 w-10 text-muted-foreground mb-2" />
                  <p className="text-sm text-muted-foreground">
                    点击或拖拽CSV文件到此处上传
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">支持 .csv 格式</p>
                </div>
              </CardContent>
              <CardFooter>
                <Button
                  onClick={() => fileInputRef.current?.click()}
                  disabled={isExecuting}
                  className="w-full"
                >
                  {isExecuting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      执行中...
                    </>
                  ) : (
                    <>
                      <Play className="mr-2 h-4 w-4" />
                      上传并执行
                    </>
                  )}
                </Button>
              </CardFooter>
            </Card>
          </TabsContent>

          <TabsContent value="result">
            <Card>
              <CardHeader>
                <CardTitle>执行结果</CardTitle>
                <CardDescription>
                  {isExecuting
                    ? "正在处理数据..."
                    : result
                      ? `执行完成，耗时: ${result.executionTime}`
                      : "尚未上传数据"}
                </CardDescription>
              </CardHeader>
              <CardContent>
                {isExecuting ? (
                  <LoadingState />
                ) : result ? (
                  <div className="space-y-4">
                    {result.error ? (
                      <Alert variant="destructive">
                        <AlertTitle>{result.error}</AlertTitle>
                        <AlertDescription>{result.details}</AlertDescription>
                      </Alert>
                    ) : (
                      <>
                        <div>
                          <h3 className="text-lg font-medium mb-2">数据摘要</h3>
                          <div className="p-4 bg-muted rounded-md">
                            <pre className="whitespace-pre-wrap">{result.result.summary}</pre>
                          </div>
                        </div>

                        <Separator />

                        <div>
                          <h3 className="text-lg font-medium mb-2">执行步骤</h3>
                          <div className="space-y-2">
                            {result.steps.map((step: string, index: number) => (
                              <div key={index} className="p-2 border rounded-md">
                                <p>{step}</p>
                              </div>
                            ))}
                          </div>
                        </div>

                        <Separator />

                        <div>
                          <h3 className="text-lg font-medium mb-2">搜索与时间控制</h3>
                          <div className="space-y-4">
                            <div className="flex flex-col space-y-4">
                              <div className="flex space-x-4">
                                <div className="flex-1">
                                  <div className="p-4 border rounded-lg">
                                    <DynamicSearchBox onSearch={handleSearch} />
                                  </div>
                                </div>
                                <div className="flex-1">
                                  <DynamicTimeline
                                    startDate={timeline.startDate}
                                    endDate={timeline.endDate}
                                    currentDate={timeline.currentDate}
                                    isPlaying={timeline.isPlaying}
                                    onDateChange={(date) => setTimeline(prev => ({ ...prev, currentDate: date }))}
                                    onPlayToggle={() => setTimeline(prev => ({ ...prev, isPlaying: !prev.isPlaying }))}
                                  />
                                </div>
                              </div>
                              <div className="h-[800px] w-full border rounded-lg overflow-hidden bg-black">
                                <DynamicGraph
                                  nodes={filteredData.nodes}
                                  links={filteredData.links}
                                  onSearch={handleSearch}
                                />
                              </div>
                            </div>
                          </div>
                        </div>
                      </>
                    )}
                  </div>
                ) : (
                  <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                    <p>请先上传CSV数据文件</p>
                  </div>
                )}
              </CardContent>
              <CardFooter>
                <Button
                  onClick={() => fileInputRef.current?.click()}
                  disabled={isExecuting}
                  className="w-full"
                >
                  {isExecuting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      执行中...
                    </>
                  ) : (
                    <>
                      <Upload className="mr-2 h-4 w-4" />
                      上传新数据
                    </>
                  )}
                </Button>
              </CardFooter>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
} 